package com.jfs.qy.utils;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacpp.avutil;
import org.bytedeco.javacv.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

import static org.bytedeco.javacpp.avutil.AV_LOG_ERROR;

/**
 * @Description 录制rtsp流工具类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/5
 */
public class JavaCVRecordUtil {

    public static void frameRecord(String inputFile, String outputFile, int audioChannel, long time) {
        FFmpegFrameGrabber grabber = null;
        FFmpegFrameRecorder recorder = null;
        try {
            //只打印错误日志
            avutil.av_log_set_level(AV_LOG_ERROR);
            // 获取视频源
            grabber = new FFmpegFrameGrabber(inputFile);
            //读取流超时时间
            grabber.setOption("stimoout", "5*1000*1000");
            grabber.setOption("rtsp_transport", "udp");
            grabber.setFrameRate(30);
            grabber.setVideoBitrate(3000000);
            // 流媒体输出地址，分辨率（长，高），是否录制音频（0:不录制/1:录制）
            recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);
            recorder.setOption("stimoout", "5*1000*1000");
            recorder.setFrameRate(30);
            recorder.setVideoBitrate(3000000);
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            grabber.start();
            recorder.start();
            Frame frame = null;
            final long startTime = System.currentTimeMillis();
            while ((frame = grabber.grabFrame()) != null && System.currentTimeMillis() - startTime <= time) {
                recorder.record(frame);
            }
            grabber.close();
            recorder.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (grabber != null) {
                    grabber.close();
                }
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
            try {
                if (recorder != null) {
                    recorder.close();
                }
            } catch (FrameRecorder.Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 截取视频帧 生成封面图
     *
     * @param filePath    文件地址
     * @param outFilePath 生成文件地址
     * @throws IOException
     */
    public static void getImage(String filePath, String outFilePath) {
        FFmpegFrameGrabber ff = null;
        try {
            File file = new File(outFilePath);
            //创建视频帧抓取工具
            ff = FFmpegFrameGrabber.createDefault(filePath);
            ff.start();
            //获取图片第一帧
            Frame frame = null;
            //获取视频的总时长
            int ftp = ff.getLengthInFrames();
            int flag = 0;
            while (flag <= ftp) {
                frame = ff.grabImage();
                //避免出现黑图
                if ((frame != null)) {
                    break;
                }
                flag++;
            }
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bufferedImage = converter.getBufferedImage(frame);
            if (Objects.nonNull(bufferedImage)) {
                ImageIO.write(bufferedImage, "jpg", file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(ff)) {
                try {
                    ff.close();
                    ff.stop();
                } catch (FrameGrabber.Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
